package com.sophossystems.client.asmon.dao.spring;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.transaction.annotation.Transactional;

import com.sophossystems.client.asmon.dao.DelegacionDao;
import com.sophossystems.client.asmon.dto.DelegacionDTO;
import com.sophossystems.client.asmon.exceptions.DaoException;

public class DelegacionDaoImpl extends AbstractDAO implements DelegacionDao {
	
	private static Logger logger = Logger.getLogger(DelegacionDaoImpl.class);

	@Override
	@Transactional
	public DelegacionDTO findByIdDelgacion(final int idDelegacion)
			throws DaoException {
		DelegacionDTO exito = null;
		try {
			exito = (DelegacionDTO) getHibernateTemplate().execute(new HibernateCallback() {
				
				@Override
				public Object doInHibernate(Session session) throws HibernateException,
						SQLException {
					final Query oQuery = session.createQuery("SELECT d.idDelegacion as idDelegacion, d.nombreDelegacion as" +
							" nombreDelegacion, d.cpInicio as cpInicio, d.cpFinal as cpFinal FROM " + 
							getTableName() + " d WHERE d.idDelegacion = :idDelegacion");
					oQuery.setInteger("idDelegacion", idDelegacion);
					DelegacionDTO delegacionDto =  (DelegacionDTO) oQuery.setResultTransformer(Transformers.aliasToBean(
							DelegacionDTO.class)).list().get(0);
					return delegacionDto;
				}
			});
		} catch (Exception e) {
			logger.debug("Error FindByIdDelegacion, causa: " + e.getCause());
			throw new DaoException("Error FindByIdDelegacion, causa: " + e.getCause());
		}
		return exito;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DelegacionDTO> findAll() throws DaoException {
		List<DelegacionDTO> exito = null;
		try {
			exito = (List<DelegacionDTO>) getHibernateTemplate().execute(new HibernateCallback() {
				
				@Override
				public Object doInHibernate(Session session) throws HibernateException,
						SQLException {
					final Query oQuery = session.createQuery("SELECT d.idDelegacion as idDelegacion, d.nombreDelegacion as" +
							" nombreDelegacion, d.cpInicio as cpInicio, d.cpFinal as cpFinal FROM " + getTableName()
							+ " d");
					List<DelegacionDTO> delegacionDto = oQuery.setResultTransformer(Transformers.aliasToBean(
							DelegacionDTO.class)).list();
					return delegacionDto;
				}
			});
			
		} catch (Exception e) {
			logger.error("Error findAll Delegacion, causa: " + e.getCause());
			throw new DaoException("Error findAll Delegacion, causa: " + e.getCause());
		}
		return exito;
	}

	public String getTableName() {
		return "Delegacion";
	} 
}
